var searchUnsafeSummery;
var captainSearch;
var goLineInfo;
require(['grid', 'topBar', 'date','highcharts'], function () {
	var goLineInfo;
    $('#top').topBar({
        left: [{
                   type: 'filter-more',
                   search: function () {
                	   search();
                   },
                   item: [
                       {
                           text: '时间快捷',
                           name1: 'beginTime',
                           name2: 'endTime',
                           hidden:true,
                           type: 'dateLine'
                       }
                   ]
               }
        ],
        right: [
            {
                text: '导出',
                type: 'export-btn',
                authority: '',
                item: [
                    {
                        text: 'Excel导出',
                        click: function () {
                        	exportFile('Excel');
                        }
                    },
                    {
                        text: 'PDF导出',
                        click: function () {
                        	exportFile('Pdf');
                        }
                    }
                ]
            }
        ]
    });
    
    function exportFile(suffix){
    	var $postData=$("#top").parent().getValues();
		if($('#grid').getGridParam("reccount")<1){
			$.messager.alert("提示","请先查询数据。","info");
			return;
		}
		$postData.statisType = 'DRV';
		var type = commonFun.getLeftTreeCurrentTreeType();
		var orgIds = commonFun.getLeftTreeCheckedNodes(type);
		if(!orgIds){
			$.messager.alert("提示","请选择查询车辆/机构/驾驶员！","info");
			return;
		}
    	$postData.type=type;
    	$postData.orgIds=orgIds;
    	var url = "/drivingBehavior/exportDrivingBehaviorStatistics2"+suffix+".htm";
    	$.exportFile(url,$postData);		
    }
    
	// 跳转到不安全行为详细页面
	function toDetailsPage(type, orgIds, drvsctbhv){
		// 传递的参数
        var val=$("#top").parent().getValues();
		var beginTime = val.beginTime;
		var endTime = val.endTime;
		$.openTab('9e9e90184a644a069ece59eca8cae9fe', 'showDriverBehaviorDetail', [type, orgIds, beginTime, endTime, drvsctbhv]);
	}
	
	// 跳转到超速详细页面
	function toOverSpeedDetailsPage(type, orgIds){
		// 传递的参数
		 var data=$("#top").parent().getValues();
			data.type=type;
	        data.orgIds = orgIds;
	        data.spedType = "";
	        $.openTab('82574146a7d34a1bb4423bafbeddbe21','showReportOverSpeedDetail',[data]);
	}

	//跳转到线路信息界面
	goLineInfo = function(lineId){
		var data = {};
		data.lineId = lineId;
		$.openTab('4db17f8a322b4749a61eb2f8a12023ae','showLineInfo',[data]);
	}

	$('#grid').parent().height($(window).height()-60);
    
    $('#grid').grid({
        multiselect:false,
        url : "/drivingBehavior/searchDrivingBehaviorStatistics.htm",
        tableId:'e063368fc8ad4d0ab011fc9a739ff1cd',
		colModel:[
			{name: "drvId", label:"drvId",hidden: true},
			{name: "lineId", label:"lineId", hidden: true},
            {name: "ranking", label:"排名",align: "right",width:40, sortable:true},
			{name: "drvName", label:"驾驶员",width:80, formatter: function(cellvalue, options, rowObject){
				if(cellvalue == null || cellvalue == ''){
					return "未知驾驶员";
				}else{
					return cellvalue;
				}
			}},
			{name: "lineName", label:"营运线路",width:80,formatter: 'customCurrency',formatoptions:{
				redbtn:true,
				css:'text-link c-blue',
				clickFn:function(rowObject,cellvalue){
					goLineInfo(rowObject.lineId);
				}
			}},
			{name: "lineAverage", label:"线路均值",width:80},
			{name: "totalbhvcount",label:"异常行为总数",align: "right",width:120, formatter:"customCurrency", formatoptions:{
				redbtn:true,
				clickFn:function(rowObject){
					toDetailsPage("DRIVER", rowObject.drvId,"");
				}
			}},
			{name: "bhv1count", label:"车辆未停稳开车门",width:160,align: "right", formatter:"customCurrency", formatoptions:{
				redbtn:true,
				clickFn:function(rowObject){
					toDetailsPage("DRIVER", rowObject.drvId,"1");
				}
			}},
			{name: "bhv2count",  label:"车辆起步不关车门",width:160, align: "right", formatter:"customCurrency", formatoptions:{
				redbtn:true,
				clickFn:function(rowObject){
					toDetailsPage("DRIVER", rowObject.drvId,"2");
				}
			}},
			{name: "bhv3count",  label:"超车",width:40, align: "right", formatter:"customCurrency", formatoptions:{
				redbtn:true,
				clickFn:function(rowObject){
					toDetailsPage("DRIVER", rowObject.drvId,"3");
				}
			}},
			{name: "bhv4count", label:"急转弯",width:80, align: "right", formatter:"customCurrency", formatoptions:{
				redbtn:true,
				clickFn:function(rowObject){
					toDetailsPage("DRIVER", rowObject.drvId,"4");
				}
			}},
			{name: "bhv5count", label:"空档滑行",width:80, align: "right", formatter:"customCurrency", formatoptions:{
				redbtn:true,
				clickFn:function(rowObject){
					toDetailsPage("DRIVER", rowObject.drvId,"5");
				}
			}},
			{name: "bhv6count", label:"倒档时车速超速报警",width:200, align: "right", formatter:"customCurrency", formatoptions:{
				redbtn:true,
				clickFn:function(rowObject){
					toDetailsPage("DRIVER", rowObject.drvId,"6");
				}
			}},
			{name: "bhv7count", label:"ABS制动",width:100, align: "right", formatter:"customCurrency", formatoptions:{
				redbtn:true,
				clickFn:function(rowObject){
					toDetailsPage("DRIVER", rowObject.drvId,"7");
				}
			}},
			{name: "bhv8count", label:"夜间行驶过长",width:120,align: "right", formatter:"customCurrency", formatoptions:{
				redbtn:true,
				clickFn:function(rowObject){
					toDetailsPage("DRIVER", rowObject.drvId,"8");
				}
			}},
			{name: "bhv9count", label:"起步急加速",width:100,align: "right", formatter:"customCurrency", formatoptions:{
				redbtn:true,
				clickFn:function(rowObject){
					toDetailsPage("DRIVER", rowObject.drvId,"9");
				}
			}},
			{name: "bhv10count", label:"熄火滑行",width:80,align: "right", formatter:"customCurrency", formatoptions:{
				redbtn:true,
				clickFn:function(rowObject){
					toDetailsPage("DRIVER", rowObject.drvId,"10");
				}
			}},
			{name: "bhv11count", label:"急加速",width:80,align: "right", formatter:"customCurrency", formatoptions:{
				redbtn:true,
				clickFn:function(rowObject){
					toDetailsPage("DRIVER", rowObject.drvId,"11");
				}
			}},
			{name: "bhv12count", label:"急减速",width:80,align: "right", formatter:"customCurrency", formatoptions:{
				redbtn:true,
				clickFn:function(rowObject){
					toDetailsPage("DRIVER", rowObject.drvId,"12");
				}
			}},
			{name: "bhv13count", label:"急刹",width:40,align: "right", formatter:"customCurrency", formatoptions:{
				redbtn:true,
				clickFn:function(rowObject){
					toDetailsPage("DRIVER", rowObject.drvId,"13");
				}
			}},
			{name: "bhv14count", label:"不文明鸣笛",width:100,align: "right", formatter:"customCurrency", formatoptions:{
				redbtn:true,
				clickFn:function(rowObject){
					toDetailsPage("DRIVER", rowObject.drvId,"14");
				}
			}},
			{name: "bhv15count", label:"斑马线不文明礼让",width:100,align: "right", formatter:"customCurrency", formatoptions:{
				redbtn:true,
				clickFn:function(rowObject){
					toDetailsPage("DRIVER", rowObject.drvId,"15");
				}
			}},
            {name: "bhv17count", label:"斑马线超速",width:100,align: "right", formatter:"customCurrency", formatoptions:{
                redbtn:true,
                clickFn:function(rowObject){
                    toDetailsPage("DRIVER", rowObject.carId,"17");
                }
            }},
			{name: "spedCnt", label:"超速",width:100,align: "right", formatter:"customCurrency"	
				, formatoptions:{
					redbtn:true,
					clickFn:function(rowObject){
						toOverSpeedDetailsPage("DRIVER",rowObject.drvId);		
					}
				}
			}
		]
	});
    
    //跳转到线路信息界面
    goLineInfo = function(lineId){
    	var data = {};
    	data.lineId = lineId;
    	$.openTab('4db17f8a322b4749a61eb2f8a12023ae','showLineInfo',[data]);
    }
    // 饼图
    function loadPieChart(series){
        $('#chart1').parent().show();
        $('#chart1').highcharts({
            chart: {
                plotBackgroundColor: null,
                plotBorderWidth: null,
                plotShadow: false
            },
            title: {
                text: ''
            },
            tooltip: {
                pointFormat: '{series.name}: <b>{point.percentage:.1f}%</b>'
            },
            plotOptions: {
                pie: {
                    allowPointSelect: true,
                    cursor: 'pointer',
                    dataLabels: {
                        enabled: true,
                        color: '#000000',
                        connectorColor: '#000000',
                        format: '<b>{point.name}</b>: {y} 次'
                    },
                    showInLegend: true
                }
            },
            legend: {
                layout: 'vertical',
                align: 'right',
                verticalAlign: 'middle',
                labelFormatter: function() {
                    return this.name;
                },
                floating: false
            },
            series: series,
            credits: {
                enabled: false
            }
        });
    }
    
    function search(){
 	   var $postData=$("#top").parent().getValues();
		$postData.statisType = 'DRV';
 	   var type =  commonFun.getLeftTreeCurrentTreeType();
	   var orgIds = commonFun.getLeftTreeCheckedNodes(type);
		if(!orgIds){
			$.messager.alert("提示","请选择查询车辆/机构/驾驶员。","info");
			return;
		}
		$postData.type=type;
		$postData.orgIds=orgIds;
		$('#grid').grid('setGridParam', {
			page:1,
			datatype: "json",
			postData: $postData
		}).trigger("reloadGrid");
		$.ajaxExt({
	    	url : "/drivingBehavior/searchDrivingBehaviorStatisticsForChart.htm",
			data:$postData
		}).done(function(result){
			if(result&&result[0]&&!$.isEmptyObject(result[0])){
                var series =[{
                    type: 'pie',
                    name: '故障统计',
                    data: [ ]
                }];
                var tips=['车辆未停稳开车门','车辆起步不关车门','超车','急转弯','空档滑行',
                    '倒档时车速超速报警','ABS制动','夜间行驶过长','起步急加速','熄火滑行',
                    '急加速','急减速','急刹','不文明鸣笛','斑马线不文明礼让','超速'];
                var seriesTemp=[];
                for(var i=0;i<15;i++){
                    //series[0].data.push({name:tips[i],y:$(result[0]).attr('bhv'+(i+1)+'count')});
                	seriesTemp.push({name:tips[i],y:$(result[0]).attr('bhv'+(i+1)+'count')});
                }
                //超速
                seriesTemp.push({name:tips[15],y:$(result[0]).attr('spedCnt')});
                var colModel = $('#grid').grid('getGridParam').colModel;
				$.each(seriesTemp,function(index,item){
					$.each(colModel,function(i,model){
						if(model.label == item.name&& !model.hidden&&item.y>0){
							series[0].data.push({name:item.name,y:item.y});
							};
					});
				});
				mySort(series[0].data);
                loadPieChart(series);
                $("#grid").setGridHeight($(window).height()-370);
            }
			else{
				$('#chart1').parent().hide();
			}
		});
    }

    function mySort(array){
		var temp;
		for (var i = 0; i < array.length; i++)
		{
			for (var j = 0; j < array.length - i; j++)
			{
				var obj1=$(array[j]);
				var obj2=$(array[j+1]);
				if (obj1.attr('y') > obj2.attr('y') ){
					temp = array[j + 1];
					array[j + 1] = array[j];
					array[j] = temp;
				}
			}
		}
	}
    
    searchUnsafeSummery = function(data){
		//切换成线路
		commonFun.showLeftTree(commonFun.lineTree);
		//勾选并展开节点
		commonFun.setCheckedNodes(data.lineId); 
		if(data.lineIds){
			commonFun.setCheckedNodes(data.lineIds); 
		}
		
    	$("a[data-val='"+data.dateType+"']","#top").click();
    };
    
    captainSearch = function(data){
    	$("a[data-val='"+data.statisType+"']",".more-area").click();
    	if(data.statisType == 'LINE'){
    		commonFun.showLeftTree(commonFun.lineTree);
    	}else{
    		commonFun.showLeftTree(commonFun.driverTree);
    	}
    	commonFun.setCheckedNodes(data.lineId); 
    	$("a[data-val='"+data.dateType+"']","#top").click();
    };
    
});
